//导入 slice
import {createSlice} from '@reduxjs/toolkit';
import { AppDispatch, RootState } from '../store';

// 定义一个接口
interface CountType {
  value: number
}

// 定义初始值
const initialState: CountType = {
  value: 1
}

//创建 slice 对象
let slice = createSlice({
  name: 'count',
  initialState: initialState,
  reducers:{
    //增加
    incre(state, action){
      state.value += action.payload;
    },
    //减少
    decre(state, action){
      state.value -= action.payload;
    }
  }
});

//获得 action creator
export let {incre, decre} = slice.actions;

//获得 reducer 函数
export default slice.reducer;

//定义 selector 函数
export const selectCount = (state: RootState) => state.count.value;

//创建一个异步的 action creator
export function asyncIncre(payload: number){
  return (dispatch:AppDispatch) => {
    setTimeout(() => {
      dispatch(incre(payload));
    }, 1000)
  }
}